/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from "react";
import { connect } from "dva";
import StandardTable from "@/components/StandardTable";
import ExpressModal from "@/components/ExpressModal";
import { Form, Input, Select, Button, Spin, DatePicker, Row, Col, Radio } from 'antd';
import { debounce } from 'lodash';
import Modal from '../Modal';
import moment from "moment/moment";

const FormItem = Form.Item
const { Option } = Select
const { RangePicker } = DatePicker;

@connect(({ payment, loading }) => ({
  payment,
  getList: loading.effects['payment/getCollectionPaymentList'],
  getPayBackList: loading.effects['payment/getPayBackList'],
  getNoPayBackList: loading.effects['payment/getNoPayBackList'],
}))
@Form.create()
class CashBackList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      company_id: "all",
      visible: false,
      title: '',
      type: null,
      recordId: null,
      data_start: moment().startOf("day").subtract(6, "days"),
      data_end: moment().endOf("day").subtract(0, "days"),
      expressInfo: null,
      isShow: false
    };
    this.columns = [  //已回款清单
      {
        title: '回款时间',
        key: 'update_at',
        dataIndex: 'update_at',
        align: 'center',
      },
      {
        title: '回款总金额（元）',
        key: 'collection_amount',
        dataIndex: 'collection_amount',
        align: 'center',
        render: (text)=><span style={{color:'red'}}>{text}</span>
      },
      {
        title: '总单号数量',
        key: 'count',
        dataIndex: 'count',
        align: 'center',
      },
      {
        title: '公司名称',
        key: 'company_name',
        dataIndex: 'company_name',
        align: 'center',
        render: (text, record) => {
          return (
            <a onClick={this.onTriggerModal.bind(this, true, record, 'client')}>{text}</a>
          )
        }
      },
      {
        title: '单号记录',
        align: 'center',
        render: (text, record) => {
          record.type = '2'
          return (
            <Button
              type='primary'
              onClick={()=>this.props.onTabChange('record',{record,time:{ //跳转至代收货款页面查询明细
                startTime: this.state.formValues.startTime,
                endTime: this.state.formValues.endTime
              }},"payBack")}
            >查看明细</Button>
          )
        }
      }
    ],
    this.noPayBackColumns = [   //未回款清单
      {
        title: '公司名称',
        key: 'company_name',
        dataIndex: 'company_name',
        align: 'center',
        render: (text, record) => {
          return (
            <a onClick={this.onTriggerModal.bind(this, true, record, 'client')}>{text}</a>
          )
        }
      },
      {
        title: '回款总金额（元）',
        key: 'collection_amount',
        dataIndex: 'collection_amount',
        align: 'center',
        render: (text)=><span style={{color:'red'}}>{text}</span>
      },
      {
        title: '总单号数量',
        key: 'count',
        dataIndex: 'count',
        align: 'center',
      },
      {
        title: '单号记录',
        align: 'center',
        render: (text, record) => {
          record.type = '1'
          return (
            <Button
              type='primary'
              onClick={()=>this.props.onTabChange('record',{record,time:{   //跳转至代收货款页面查询明细
                startTime: this.state.formValues.startTime,
                endTime: this.state.formValues.endTime
              }},"noPayBack")}
            >查看明细</Button>
          )
        }
      },
      {
        title: '操作',
        align: 'center',
        render: (text, record) => {
          return (
            <Button
              type='primary'
              onClick={this.onTriggerModal.bind(this, true, record, "checkNoBack")}
            >核销</Button>
          )
        }
      },
    ]
  }

  componentDidMount() {
    const { dispatch, form } = this.props

    this.getFormValues(values=>{
      dispatch({
        type: 'payment/getPayBackList',
        payload: {
          ...values
        }
      })
    })
  }

  getFormValues = then => {
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      const { date } = fieldsValue;
      if (date) {
        values.date = date.map(d => moment(d).format("YYYY-MM-DD"));
        const [start, end] = values.date;
        values.startTime = start;
        values.endTime = end;
        delete values.date;
      }
      this.setState({
        formValues: values,

      });
      then(values);
    });
  };

  handleSearch = debounce(e => {
    e.preventDefault();
    const { dispatch } = this.props;
    const { isShow } = this.state
    this.getFormValues(values=>{
      let url = isShow ? 'payment/getNoPayBackList' : 'payment/getPayBackList'
      dispatch({
        type: url,
        payload: {
          ...values
        }
      })
    })
  }, 500, {
    leading: true,
    trailing: false
  });

  onTriggerModal(open, record, type) {
    this.formRef.props.form.resetFields()
    this.setState({
      visible: open,
      record,
      type
    })
  }

  // 展示物流
  showExpressModal = data => {
    const { brand, brand_cn, waybill_no } = data;
    this.setState({
      expressInfo: {
        brand,
        waybill_no,
        brand_name: brand_cn,
        visible: false
      }
    });
  };

  onSwitchChange = (e) => {
    let value = e.target.value
    const { dispatch } = this.props
    this.getFormValues(values=>{
      let url = value ? "payment/getNoPayBackList" : "payment/getPayBackList"
      
      dispatch({
        type: url,
        payload:{
          ...values
        }
      })
    })

    this.setState({isShow:value})
  }

  modalFormRef = formRef => {
    this.formRef = formRef;
  };

  disabledDate = (current) => {
    // Can not select days before today and today
    return current && current > moment().endOf("day").subtract(0, "days");
  };

  render() {
    const { visible, isShow, type, record, data_end, data_start, expressInfo, formValues } = this.state
    const {
      form: { getFieldDecorator },
      getList,
      getPayBackList,
      getNoPayBackList,
      payment: { paymentList, payBackList, noPayBackList },
    } = this.props;

    return (
      <div>
        <Form
          layout='inline'
          style={{ marginBottom: 24 }}
          className="search-form"
        >
          <FormItem >
            {
              getFieldDecorator("date", {
                initialValue: [moment(data_start), moment(data_end)]
              })(
                <RangePicker
                  style={{ width: 350 }}
                  disabledDate={this.disabledDate}
                  placeholder={["开始日期", "结束日期"]}
                />
              )
            }
          </FormItem>
          <FormItem>
            {getFieldDecorator(`search`, {
              initialValue: ''
            })(<Input allowClear style={{ width: 250 }} placeholder="请输入客户手机或者姓名搜索" />)}
          </FormItem>
          <FormItem>
            <Button
              type="primary"
              icon="search"
              onClick={this.handleSearch}
              loading={getList}
            >查询</Button>
          </FormItem>
        </Form>
        <Row style={{marginBottom:20}}>
          <Col>
            <Radio.Group defaultValue={isShow} buttonStyle="solid" onChange={this.onSwitchChange}>
              <Radio.Button value={false}>已回款记录</Radio.Button>
              <Radio.Button value={true}>未回款统计</Radio.Button>
            </Radio.Group>
          </Col>
        </Row>
        {
          !isShow ? (
            <StandardTable  //已回款统计记录
              rowKey={record => record.update_at}
              columns={this.columns}
              data={payBackList}
              loading={getPayBackList}
            />
          ) : (
            <StandardTable  //未回款统计
              rowKey={record => record.id}
              columns={this.noPayBackColumns}
              data={noPayBackList}
              loading={getNoPayBackList}
            />
          )
        }
        
        <ExpressModal
          cleanData={() => {
            this.setState({
              expressInfo: null,
            });
          }}
          data={expressInfo}
        />
        <Modal
          wrappedComponentRef={this.modalFormRef}
          visible={visible}
          type={type}
          record={record}
          hideModal={() => this.onTriggerModal(false)}
          searchVale={formValues}
        />
      </div>
    );
  }
}

export default CashBackList;